//
//  SXComposeView.swift
//  sina
//
//  Created by shengxinwei on 16/5/28.
//  Copyright © 2016年 shengxinwei. All rights reserved.
//

import UIKit
import SnapKit


class SXComposeView: UIView {
    
    //存放按钮数组
    private lazy var buttons: [SXComposeBtn] = [SXComposeBtn]()
    
    weak var targetVc: UIViewController?
    
    
    override init(frame: CGRect) {
        let rect = UIScreen.mainScreen().bounds
        super.init(frame: rect)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //将控制器当成参数传入
    func show(targetVc target: UIViewController) {
        self.targetVc = target
        //把自己添加到控制器上
        target.view.addSubview(self)
        
    }
    
    private func setupUI() {
        addSubview(backView)
        addSubview(sloganView)
        
        sloganView.snp_makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.top.equalTo(100)
        }
        //添加按钮
        addchildButtons()
    }
    
    //移动到父视图上做动画
    override func willMoveToSuperview(newSuperview: UIView?) {
        super.willMoveToSuperview(newSuperview)
        //通过循环分别给按钮添加动画
        for (index,btn) in buttons.enumerate() {
            startAnimation(btn, index: index, offset: -350)
        }
        
    }
    
    private func startAnimation(btn: SXComposeBtn,index: Int,offset: CGFloat) {
        UIView.animateWithDuration(Double(index) * 0.02, delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 5, options: [], animations: {
            //按钮向上位移
            btn.center = CGPoint(x: btn.center.x, y: btn.center.y + offset)
            }) { (_) in
                if(offset > 0){
                    self.removeFromSuperview()
                }
        }
    }
    
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        for (index,btn) in buttons.reverse().enumerate() {
            startAnimation(btn, index: index, offset: 350)
        }
    }
    
    private func addchildButtons() {
        let count = composeArr.count
        
        //按钮宽高
        let w: CGFloat = 80
        let h: CGFloat = 120
        let margin: CGFloat = (ScreenWidth - w * 3) / 4
        
        for i in 0..<count {
            let itemCompose = composeArr[i]
            let btn = SXComposeBtn()
            btn.composeModel = itemCompose
            let row = i / 3
            let col = i % 3
            let x = CGFloat(col) * (margin + w) + margin
            let y = CGFloat(row) * (h + margin) + ScreenHeight // - 350
            btn.frame = CGRect(x: x, y: y, width: w, height: h)
            
            btn.addTarget(self, action: #selector(SXComposeView.btnClick(_:)), forControlEvents: .TouchUpInside)
            //btn.backgroundColor = UIColor.redColor()
            addSubview(btn)
            //添加到数组中
            buttons.append(btn)
        }
        
    }
    
    
    //MARK: - 按钮点击事件
    @objc private func btnClick(btn: SXComposeBtn) {
        for button in buttons {
            var scale: CGFloat = 0
            //是否是被点击的按钮,,如果是的话,将这个按钮放大,其他按钮缩小
            if button == btn {
                scale = 2.0
            }else {
                scale = 0.2
            }
            
            UIView.animateWithDuration(0.25, animations: {
                button.alpha = 0
                button.transform = CGAffineTransformMakeScale(scale, scale)
                }, completion: { (_) in
                    
            })
        }
        
        guard let targetStr = btn.composeModel?.target else{
            return
        }
 
        
        //根据字符串来获取控制器的类型
        let vcType = NSClassFromString(targetStr) as! UIViewController.Type
        //初始化控制器
        let vc = vcType.init()
        //将控制器添加入导航控制器中
        let nav = UINavigationController(rootViewController: vc)
        //跳转界面
        targetVc?.presentViewController(nav, animated: true, completion: {
            //移除视图
            self.removeFromSuperview()
        })
    }
    

    //MARK: - 懒加载
    private lazy var backView: UIImageView =  UIImageView(image: UIImage.snapShotCurrentWindow().applyDarkEffect())
    
    
    //分享图片
    private lazy var sloganView: UIImageView = UIImageView(image: UIImage.init(named: "compose_slogan"))
    
    lazy var composeArr: [SXCompose] = {
        var arr = [SXCompose]()
        //加载plist文件路径
        let path = NSBundle.mainBundle().pathForResource("Compose.plist", ofType: nil)!
        //将数据存放如数组
        let itemArr = NSArray(contentsOfFile: path) as! [[String: AnyObject]]
        for dict in itemArr {
            //字典转模型
            arr.append(SXCompose(dict: dict))
        }
        return arr
    }()
}
